package org.jiajie.coffeecodes.concurrent.poison;

import java.util.Arrays;

/**
 * @author jay
 */
public class Task {
    private String[] stepNames = {"step1","step2","step3","step4"};
    private int currentIndex = 0;
    private TaskCancelManager manager = new TaskCancelManager();

    public void execute() {
        System.out.println("任务开始执行 steps=" + Arrays.asList(stepNames));
        Step currStep = null;
        while (true) {
            if (currentIndex + 1 > stepNames.length) {
                break;
            }
            // 执行任务
            String stepName = stepNames[currentIndex];
            boolean success = manager.addStep(stepName);
            if (!success){
                System.out.println(stepName + " 不继续执行");
                // 清理上一个步骤的数据
                if (currStep != null) {
                    currStep.purge();
                }
                break;
            }
            // 获取当前步骤，并执行
            currStep = new Step(stepName);
            currStep.execute();
            currentIndex++;
        }
        System.out.println("任务开始执行 steps=" + manager.getStepNames());
    }

    public void cancel() {
        manager.addPoison();
    }
}
